import urllib, urllib2
import django.utils.simplejson as jsondata
from conf.YoutubeConf import YoutubeConf
import sys
class VideoData:

    def processUrl(self,url):
        try:
            f = urllib2.urlopen(url)
            json = f.read()
            #return HttpResponse('Video title: %s' % json)
        
            import re    
            new_str = re.sub('[$]', '', json)
            json = jsondata.JSONDecoder().decode(new_str) 
            return json
        except:
            return '[{"text":"Looks like Twitter is down. Thanks for visiting us. Please try again latter."}]'
            #return sys.exc_info()[1]
            raise

    def getUserName(self):
        conf = YoutubeConf()
        userName = conf.getusername()
        return userName
    
    def getFavorites(self):
        userName = self.getUserName()
        url = 'http://gdata.youtube.com/feeds/api/users/'+userName+'/favorites?alt=json&max-results=4' 
        json = self.processUrl(url)
        return json
    
    def getPlaylist(self):
        userName = self.getUserName()
        url = 'http://gdata.youtube.com/feeds/api/users/'+userName+'/playlists?alt=json&max-results=4'
        json = self.processUrl(url)
        return json
    
    def getPlaylistInfo(self,playlistId):
        url = 'http://gdata.youtube.com/feeds/api/playlists/'+playlistId+'?alt=json&max-results=4'
        json = self.processUrl(url)
        return json
    
    def getSubscription(self):
        userName = self.getUserName()
        url='http://gdata.youtube.com/feeds/api/users/'+userName+'/subscriptions?alt=json&max-results=4'        
        json = self.processUrl(url)
        return json